/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.e2e.haiti.infrastructure.surveyor;

import com.e2e.haiti.infrastructure.surveyor.httpPostHelper;
import com.e2e.haiti.infrastructure.surveyor.FragmentDemographicsQuestionnaire;

import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
//import com.actionbarsherlock.view.MenuInflater;

import android.view.MenuInflater;
import com.e2e.haiti.infrastructure.surveyor.R;

//import android.app.AlertDialog;
//import android.app.Dialog;

import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;


import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class StructureList extends SherlockListActivity {   
   
	public Context mContext;
    private ListView mainListView = null;
    CustomSqlCursorAdapter adapter = null;
    private Cursor currentCursor = null;
    private Utils utilsHelper = null;
    
    private int structureID;

    private ListView listView = null;
    
    private static final int ADD_ACTION_MENU = 1;

    private static final int STRUCTURE_ADD_DIALOG_ID = 0;
    private static final int STRUCTURE_EDIT_DIALOG_ID = 1;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0,ADD_ACTION_MENU,0, "New")
            .setIcon(R.drawable.ic_compose)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);   
       
       return true; 
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.structure_list_view);


        Intent intent = getIntent();
        String path = intent.getStringExtra("com.example.android.apis.Path");

        if (path == null) {
            path = "";
        }        
        
        // Caputures application activity to the mContext variable
        mContext = this;
       
        // Creates the dbHelper object and opens the database
        utilsHelper = new Utils(mContext); 
    	utilsHelper.openDatabase();             
       //new SelectDataTask().execute();
        
     // Ensures the database is closed to try and avoid the memory leaks that occured
        //utilsHelper.openDatabase();                	
        currentCursor = utilsHelper.dbHelper.getCursor(null);
        
        //startManagingCursor(currentCursor);
        int[] listFields = new int[] { R.id.structure_title };
        String[] dbColumns = new String[] { SqlHelper.COLUMN_STRUCTURE_NAME };

        startManagingCursor(currentCursor);
        adapter = new CustomSqlCursorAdapter(
                this, R.layout.structure_item,
                currentCursor, dbColumns, listFields,
                utilsHelper.dbHelper);
        setListAdapter(adapter);    
        
        
       setupListView(); 


    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ADD_ACTION_MENU:
            	showDialog(STRUCTURE_ADD_DIALOG_ID);           	                       	            
                return true;           
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private void setupListView(){  
 	
        listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        this.mainListView = getListView();
        mainListView.setCacheColorHint(0);
        
        registerForContextMenu(listView);

    }
    
    
    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        
        structureID = (int)id;
        utilsHelper.startNextActivity(structureID, Questionnaire.class);

    }
    
    @Override
    protected void onResume() {
        super.onResume();        
        utilsHelper.openDatabase();
       // new SelectDataTask().execute();
    	
        
    }
          
//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        
//        utilsHelper = new Utils(mContext); 
//    	utilsHelper.openDatabase();
//        new SelectDataTask().execute();
//    }

    @Override
    protected void onPause() {
        super.onPause();
        utilsHelper.closeDatabase();
    }
//    
//    @Override
//    protected void onStop() {
//      super.onStop();
//    	utilsHelper.closeDatabase();
//    }
    
    private class SelectDataTask extends AsyncTask<Void, Void, String> {
        
    	private ProgressDialog pdia;
        
    	@Override
        protected void onPreExecute(){ 
                pdia = new ProgressDialog(mContext);
                pdia.setMessage("Loading Structures ...");
                pdia.show();    
        }

        protected String doInBackground(Void... params) {

            try {
               // Ensures the database is closed to try and avoid the memory leaks that occured
               //utilsHelper.openDatabase();                	
               StructureList.this.currentCursor = utilsHelper.dbHelper.getCursor(null);

            } catch (SQLException sqle) {

                throw sqle;

            }
            return null;
        }

        protected void onPostExecute(final String result) {

        	pdia.dismiss(); 
            startManagingCursor(StructureList.this.currentCursor);
            int[] listFields = new int[] { R.id.structure_title };
            String[] dbColumns = new String[] { SqlHelper.COLUMN_STRUCTURE_NAME };

            StructureList.this.adapter = new CustomSqlCursorAdapter(
                    StructureList.this, R.layout.structure_item,
                    StructureList.this.currentCursor, dbColumns, listFields,
                    utilsHelper.dbHelper);
            setListAdapter(StructureList.this.adapter);            
        }
    }

    // A pop-up dialog is created to allow the user to create and edit a structure. 
    // REQ 3.3.4.R1 met
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.structure_list_menu, menu);
    }
    
    @Override
    public boolean onContextItemSelected(android.view.MenuItem item ) {

    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
     
        structureID = utilsHelper.dbHelper.getStructureID(currentCursor);
        
        switch (item.getItemId()) {
        
	        case R.id.openStructure:
	            utilsHelper.startNextActivity(structureID, Questionnaire.class);
	            return true;
	        
	        case R.id.editStructure:
	        	showDialog(STRUCTURE_EDIT_DIALOG_ID);	     
	            return true;
	        
	        case R.id.deleteStructure:
	        	//TODO: Create a "are you sure, prompt"
	        	utilsHelper.openDatabase();
	        	utilsHelper.dbHelper.delete_byID(structureID);
           	    updateList();        	
	            return true;
	            
	        case R.id.uploadStructure:
	        	
	        	httpPostHelper httpPost= new httpPostHelper (mContext);
	        	httpPost.postToRemoteDatabase(structureID);

	            return true;
       
        }
        return false;
    }   
          
    @Override
    protected Dialog onCreateDialog(int id) {
		
            switch (id) {

            case STRUCTURE_ADD_DIALOG_ID:
        		                      		
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                   
                    // Inflates the custom xml file layout create_structure_dialog.xml
                    LayoutInflater inflater = this.getLayoutInflater();    
                    View  dialogView  =  inflater.inflate(R.layout.create_structure_dialog,null);
                    builder.setView(dialogView);
                    
                    builder.setTitle(R.string.structure_add_dialog_title);
                    //builder.setIcon(R.drawable.icon);    
                    
                    final EditText Edit_structureNameNew = (EditText) dialogView.findViewById(R.id.editStructureName);     
            		final EditText Edit_structureDescNew = (EditText) dialogView.findViewById(R.id.editStructureDescription);
                    
                    builder.setPositiveButton(R.string.save,
                    		          
                                    new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                
                                            	// Defines strings input in by the user
                                                String structureName = Edit_structureNameNew.getText().toString();
                                                String structureDesc = Edit_structureDescNew.getText().toString();
                                            	
                                                // Adds the user-defined structure to  the database
                                                utilsHelper.openDatabase();                	
                                                utilsHelper.dbHelper.createStructureEntry(structureName, structureDesc);        
                                                
                                                // Refersehs the list  view screen with new changes                                              
                                                updateList();
                                                
                                                return;
                                            }
                                    });

                    builder.setNegativeButton(android.R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {                                                   
                                                    return;
                                            }
                                    });    
                    
                    Dialog structureDialog = builder.create();

                    return structureDialog;
                    
            case STRUCTURE_EDIT_DIALOG_ID:
          		
                AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
               
                // Inflates the custom xml file layout create_structure_dialog.xml
                LayoutInflater inflater2 = this.getLayoutInflater();    
                View  dialogView2  =  inflater2.inflate(R.layout.create_structure_dialog,null);
                builder2.setView(dialogView2);
                
                builder2.setTitle(R.string.structure_edit_dialog_title);
                //builder2.setIcon(R.drawable.icon);    
                
                final EditText Edit_structureNameEdit = (EditText) dialogView2.findViewById(R.id.editStructureName);     
        		final EditText Edit_structureDescEdit = (EditText) dialogView2.findViewById(R.id.editStructureDescription);
                
                builder2.setPositiveButton(R.string.save,
                		          
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            
                                        	// Defines strings input in by the user
                                            String structureName = Edit_structureNameEdit.getText().toString();
                                            String structureDesc = Edit_structureDescEdit.getText().toString();
                                        	
                                            // Updates the user-defined structure to  the database
                                            //structureID = adapter.getCursor().getInt(adapter.getCursor().getColumnIndex(SqlHelper.COLUMN_ID));
                                            String[][] databaseUpdates = {
                                                    {SqlHelper.COLUMN_STRUCTURE_NAME, structureName},
                                                    {SqlHelper.COLUMN_STRUCTURE_DESC, structureDesc} 
                                                    };

                                            utilsHelper.openDatabase();                	
                                            utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
                                           // utilsHelper.closeDatabase();                	
                    
                                                                 
                                            // Refersehs the list  view screen with new changes                                              
                                            updateList();
                                            
                                            return;
                                        }
                                });

                builder2.setNegativeButton(android.R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {                                                   
                                                return;
                                        }
                                });    
                
                Dialog structureDialogEdit = builder2.create();

                return structureDialogEdit;
        }
            
            
            return null;
                                                  
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {   	
 
        switch (id) { 
            case STRUCTURE_ADD_DIALOG_ID:
                // Clear the input box.
            	final EditText structureNameNew = (EditText) dialog.findViewById(R.id.editStructureName);     
        		final EditText structureDescNew = (EditText) dialog.findViewById(R.id.editStructureDescription);
        		
        		//Clear the EditText fields
        		structureNameNew.setText(""); 
        		structureNameNew.requestFocus();
        		structureDescNew.setText("");
                break;
                
            case STRUCTURE_EDIT_DIALOG_ID:

            	final EditText structureNameEdit = (EditText) dialog.findViewById(R.id.editStructureName);     
        		final EditText structureDescEdit = (EditText) dialog.findViewById(R.id.editStructureDescription);
            	
        		//Clear the EditText fields
        		String oldName = this.currentCursor.getString(this.currentCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME));
        		String oldDesc = this.currentCursor.getString(this.currentCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_DESC));
        		
        		structureNameEdit.setText(oldName); 
        		structureNameEdit.requestFocus();
        		structureDescEdit.setText(oldDesc);
                break;            	
                
            default:
            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Structure DIALOG ID");
            	break;
        }
    }
    
      
    private void updateList(){   	
        // Refreshes the list view  to incorporate the newly added/deleted structure
//        currentCursor = utilsHelper.dbHelper.getCursor(null);
//        
////        startManagingCursor(currentCursor);
////        int[] listFields = new int[] { R.id.structure_title };
////        String[] dbColumns = new String[] { SqlHelper.COLUMN_STRUCTURE_NAME };
//
////        adapter = new CustomSqlCursorAdapter(
////                this, R.layout.structure_item,
////                currentCursor, dbColumns, listFields,
////                utilsHelper.dbHelper);
////        setListAdapter(adapter); 
        currentCursor.requery();
        adapter.notifyDataSetChanged();
//        adapter.changeCursor(currentCursor);


    }      
}
